package com.alimama.serviceImpl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alimama.commoms.ResultCode;
import com.alimama.commoms.ResultData;
import com.alimama.dao.ICustDao;
import com.alimama.entity.shop.Acct;
import com.alimama.entity.shop.Cust;
import com.alimama.shop.service.ICustService;
import com.alimama.utils.MD5Utils;
import com.alimama.utils.StringUtils;

@Service("custService")
public class CustServiceImpl implements ICustService {
	
	
	private static final Logger logger = LoggerFactory.getLogger(CustServiceImpl.class);

	@Resource
	ICustDao custDao;
	
	/**
	 * 登陆
	 */
	@Override
	public ResultData login(String custMbl, String pwd)  throws Exception {
			ResultData resultData = new ResultData();
			Cust cust = custDao.queryByCustMblOrCustEmail(custMbl);
			
			if(cust == null){
				resultData.parse(ResultCode.USER_ALREADY_NOT_EXISTS);
				return resultData;
			}
			
			// 验证密码是否正确 
			if (!pwd.equals(cust.getCustPwd())) {
				resultData.parse(ResultCode.PASSWORD_ERROR);
				return resultData;
			} 
			
			// 成功
			resultData.parse(ResultCode.SUCCESS);
			resultData.setData(cust);
			return resultData;
	}

	/**
	 * 注册
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResultData register(String custMblOremail,String password)  throws Exception{

		ResultData resultData = new ResultData();
		
		try {
			
			Cust cust = custDao.queryByCustMblOrCustEmail(custMblOremail);
			if (cust != null) {
				resultData.parse(ResultCode.USER_ALREADY_EXISTS);
				return resultData;
			}
			
			cust = new Cust();
			cust.setCustMbl(custMblOremail);
			cust.setCustPwd(MD5Utils.md5Encode(password));
			custDao.add(cust);//TODO
			 
			Acct acct  = new Acct();
			acct.setCustId(cust.getId());
			acct.setAcctNo(StringUtils.getUUID());//随机生成一个账户编号
			//acctDao.insert(acct);
			 
			resultData.parse(ResultCode.SUCCESS);
			
		} catch (Exception e) {
			resultData.parse(ResultCode.SYSTEM_ERROR);
			logger.error("CustServiceImpl.register.error:",e);
			throw e;
		}
		return resultData;
	}

	@Override
	public Cust queryBycustMbl(String custMbl) throws Exception {
		return custDao.queryByCustMblOrCustEmail(custMbl);
	}

}
